//
//  ContactViewController.m
//  Exam16-2
//
//  Created by 孙晓晔 on 2017/5/31.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "ContactViewController.h"

#import "ChatViewController.h"
#import "AddFriendViewController.h"
#import "ApplyViewController.h"

@interface ContactViewController ()<EMContactManagerDelegate,EMUserListViewControllerDelegate>

@property (strong, nonatomic) NSMutableArray *contactsSource;
@property (nonatomic) NSInteger unapplyCount;

@end

@implementation ContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[EMClient sharedClient].contactManager addDelegate:self delegateQueue:nil];
    
}

- (void)reloadApplyView {
    NSInteger count = [[[ApplyViewController shareController] dataSource] count];
    self.unapplyCount = count;
    [self.tableView reloadData];
}

- (void)reloadDataSource
{
    [self.dataArray removeAllObjects];
    [self.contactsSource removeAllObjects];
    
    NSArray *buddyList = [[EMClient sharedClient].contactManager getContacts];
    
    for (NSString *buddy in buddyList) {
        [self.contactsSource addObject:buddy];
    }
//    [self _sortDataArray:self.contactsSource];
    
    [self.tableView reloadData];
}

- (void)userListViewController:(EaseUsersListViewController *)userListViewController
            didSelectUserModel:(id<IUserModel>)userModel {
    NSLog(@"userListViewController", nil);
}

#pragma mark - EMContactManagerDelegate

// 同意添加好友
- (void)friendRequestDidApproveByUser:(NSString *)aUsername {
    NSLog(@"同意添加好友", nil);
}

// 拒绝添加好友
- (void)friendRequestDidDeclineByUser:(NSString *)aUsername {
    NSLog(@"拒绝添加好友", nil);
}

// 删除好友
- (void)friendshipDidRemoveByUser:(NSString *)aUsername {
    NSLog(@"friendshipDidRemoveByUser", nil);
    
    EaseUserModel *user = [[EaseUserModel alloc] initWithBuddy:aUsername];
    
    [self.dataArray removeObject:user];
    [self.contactsSource removeObject:aUsername];
    
    [self.tableView reloadData];
}

// 添加好友
- (void)friendshipDidAddByUser:(NSString *)aUsername {
    
    EaseUserModel *user = [[EaseUserModel alloc] initWithBuddy:aUsername];
    
    [self.dataArray addObject:user];
    
    [self.tableView reloadData];
    
    NSLog(@"friendshipDidAddByUser", nil);
}

// 处理被添加为好友申请
- (void)friendRequestDidReceiveFromUser:(NSString *)aUsername
                                message:(NSString *)aMessage {
    NSLog(@"friendRequestDidReceiveFromUser", nil);
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"title":aUsername, @"username":aUsername, @"applyMessage":aMessage, @"applyStyle":[NSNumber numberWithInteger:ApplyStyleFriend]}];
    [[ApplyViewController shareController] addNewApply:dic];
}

- (void)userListViewController:(EaseUsersListViewController *)userListViewController
            didDeleteUserModel:(id<IUserModel>)userModel {
    NSLog(@"didDeleteUserModel", nil);
    
}

// 添加联系人，显示搜索
- (IBAction)addContact:(id)sender {
    AddFriendViewController *addController = [[AddFriendViewController alloc] init];
    [self.navigationController pushViewController:addController animated:YES];
}

// 添加联系人
- (void)addFriendAction {
    AddFriendViewController *addController = [[AddFriendViewController alloc] init];
    [self.navigationController pushViewController:addController animated:YES];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (section == 0) {
        return 1;
    }
    
    return [self.dataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *CellIdentifier = [EaseUserCell cellIdentifierWithModel:nil];
    EaseUserCell *cell = (EaseUserCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    // Configure the cell...
    if (cell == nil) {
        cell = [[EaseUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    if (indexPath.section == 0) {
        NSString *CellIdentifier = @"addFriend";
        EaseUserCell *cell = (EaseUserCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[EaseUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        
        cell.avatarView.image = [UIImage imageNamed:@"newFriends"];
        cell.titleLabel.text = @"申请与通知";
        cell.avatarView.badge = self.unapplyCount;
        return cell;
        
        // return nil;
    } else {
        id<IUserModel> model = nil;
        if ([self.dataSource respondsToSelector:@selector(userListViewController:userModelForIndexPath:)]) {
            model = [self.dataSource userListViewController:self userModelForIndexPath:indexPath];
        } else {
            model = [self.dataArray objectAtIndex:indexPath.row];
        }
        
        if (model) {
            cell.model = model;
        }
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    if (section == 0) {
        if (row == 0) {
            [self.navigationController pushViewController:[ApplyViewController shareController] animated:YES];
        }
    } else {
     
        id<IUserModel> model = nil;
        if (self.dataSource && [self.dataSource respondsToSelector:@selector(userListViewController:userModelForIndexPath:)]) {
            model = [self.dataSource userListViewController:self userModelForIndexPath:indexPath];
        }
        else {
            model = [self.dataArray objectAtIndex:indexPath.row];
        }
        
        if (model) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(userListViewController:didSelectUserModel:)]) {
                [self.delegate userListViewController:self didSelectUserModel:model];
            } else {
                EaseMessageViewController *viewController = [[EaseMessageViewController alloc] initWithConversationChatter:model.buddy conversationType:EMConversationTypeChat];
                viewController.title = model.nickname;
                [self.navigationController pushViewController:viewController animated:YES];
            }
        }
    }
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        
        id<IUserModel> model = self.dataArray[indexPath.row];
        
        EMError *error = [[EMClient sharedClient].contactManager deleteContact:model.buddy isDeleteConversation:YES];
        if (!error) {
            NSLog(@"删除成功");
            
            [self.tableView beginUpdates];
            [self.dataArray removeObjectAtIndex:indexPath.row];
            [self.contactsSource removeObject:model.buddy];
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView endUpdates];
        }
        
    }
}

@end
